package com.cn.onetrip.view;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

import com.cn.onetrip.activity.R;
import com.cn.onetrip.objects.PointAudioObj;
import com.cn.onetrip.objects.RoutePointObj;
import com.cn.onetrip.untility.SysApplication;

public class AudioPlayLayout extends RelativeLayout implements OnClickListener {

	public static final int START_PLAY = 0;
	public static final int UPDATE_TIME = 1;
	public static final int START_OTHER_AUDIO = 2;
	public static final int STOP_PLAY = 3;
	public static final int PAUSE_PLAY = 4;
	public static final int RESTART_PLAY = 5;
	public static final int SCREEN_LOCK = 9;

	public int titleTopOffset = 14;

	public int LeastID = -1;

	private Context context;
	private ImageView imagePlayBtn;
	public TextView textTitle;

	private PointAudioObj audioObj;
	private int pointIndex;
	private int pointType;

	public Point ptStart;
	public Point ptEnd;
	public double degree;
	public Animation animation;
	public boolean hasPopup = false;

	public Handler parentHandler;

	private MediaPlayer mp = null;
	private Thread voiceThread = null;

	public boolean isPlaying = false;
	public boolean isTitleDown = true;
	public boolean isPauseing = false;
	public boolean isPrepered = false;

	public AudioPlayLayout(Context context) {
		super(context);
		this.context = context;
	}

	public AudioPlayLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
	}

	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();

		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(dm);

		int screenWidth = dm.widthPixels;
		if (screenWidth <= 800) {
			titleTopOffset = 10;
		}

		imagePlayBtn = (ImageView) findViewById(R.id.button_play);
		// textTitle = (TextView) findViewById(R.id.text_title);
		textTitle = new TextView(context);
		textTitle.setTextColor(Color.WHITE);
		textTitle.setGravity(Gravity.CENTER);
		textTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources()
				.getDimensionPixelSize(R.dimen.audio_title_size));

		if (imagePlayBtn != null) {
			imagePlayBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Message msg = new Message();
					if (isPlaying) {
						// msg.what = STOP_PLAY;
						// closeAudio();
						msg.what = PAUSE_PLAY;
						msg.arg1 = audioObj.index;
						pauseAudio();
					} else {
						if (isPauseing && isPrepered) {
							msg.what = RESTART_PLAY;
							msg.arg1 = audioObj.index;
						} else {
							msg.what = START_OTHER_AUDIO;
							msg.arg1 = audioObj.index;
						}
					}
					parentHandler.sendMessage(msg);
				}
			});
		}
	}

	public void setHandler(Handler handler) {
		this.parentHandler = handler;
	}

	@Override
	public Handler getHandler() {
		return parentHandler;
	}

	public void setAudioData(PointAudioObj audioObj, int pointIndex,
			int pointType) {
		this.audioObj = audioObj;
		this.pointIndex = pointIndex;
		this.pointType = pointType;

		int drawableID = getResources().getIdentifier("other_play", "drawable",
				context.getPackageName());
		;
		if (pointType == RoutePointObj.TYPE_IN_LINE) {
			int index = (pointIndex + 1) % (SysApplication.POP_NUM / 2);
			drawableID = getResources().getIdentifier("play" + index,
					"drawable", context.getPackageName());
		}

		imagePlayBtn.setBackgroundResource(drawableID);

		textTitle.setText(audioObj.name);
	}

	public void setTitlePosition(boolean isTitleDown) {
		this.isTitleDown = isTitleDown;

		// Drawable drawable = context.getResources().getDrawable(
		// isPlaying() ? R.drawable.play1 : R.drawable.pause1);

		RelativeLayout.LayoutParams lpTitle = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		int left = (int) (ptEnd.x - getWidth() / 2 - (textTitle.getWidth() - getWidth()) / 2);
		int top = (int) (isTitleDown ? (ptEnd.y + getHeight() / 2 - titleTopOffset)
				: (ptEnd.y - getHeight() / 2 - textTitle.getHeight())
						+ titleTopOffset);
		lpTitle.setMargins(left, top, 0, 0);
		textTitle.setLayoutParams(lpTitle);
	}

	public void setTitleVisible(int visibility) {
		textTitle.setVisibility(visibility);
	}

	public boolean isPlaying() {
		return isPlaying;
	}

	private void setPlayBtnResource(boolean isPlay) {
		String name = isPlay ? "play" : "pause";
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		Drawable daPlay = getResources().getDrawable(R.drawable.play1);
		Drawable daPause = getResources().getDrawable(R.drawable.pause1);

		int drawableID = 0;
		if (pointType == RoutePointObj.TYPE_IN_LINE) {
			int index = (pointIndex + 1) % (SysApplication.POP_NUM / 2);
			drawableID = getResources().getIdentifier(name + index, "drawable",
					context.getPackageName());
		} else {
			drawableID = getResources().getIdentifier("other_" + name,
					"drawable", context.getPackageName());
		}

		// int left = imagePlayBtn.getLeft()
		// - (daPause.getIntrinsicWidth() - daPlay.getIntrinsicWidth())
		// / 2;
		// int top = imagePlayBtn.getTop()
		// - (daPause.getIntrinsicHeight() - daPlay.getIntrinsicHeight())
		// / 2;
		// if (isPlay) {
		// left = imagePlayBtn.getLeft()
		// + (daPause.getIntrinsicWidth() - daPlay.getIntrinsicWidth())
		// / 2;
		// top = imagePlayBtn.getTop()
		// + (daPause.getIntrinsicHeight() - daPlay
		// .getIntrinsicHeight()) / 2;
		// }
		//
		// lp.setMargins(left, top, 0, 0);
		//
		// imagePlayBtn.setLayoutParams(lp);
		imagePlayBtn.setBackgroundResource(drawableID);
	}

	@Override
	public void onClick(View v) {
		// switch (v.getId()) {
		// case R.id.button_play: {
		// Message msg = new Message();
		// if (isPlaying) {
		// msg.what = STOP_PLAY;
		// closeAudio();
		// } else {
		// msg.what = START_OTHER_AUDIO;
		// msg.obj = audioObj.index;
		// }
		//
		// parentHandler.sendMessage(msg);
		// }
		// break;
		//
		// default:
		// break;
		// }

	}

	public void play() {
		isPlaying = true;
		setPlayBtnResource(false);

		Message msg = new Message();
		msg.what = START_PLAY;
		parentHandler.sendMessage(msg);

		startPlayAudio();
	}

	private void startPlayAudio() {

		if (mp == null) {
			mp = new MediaPlayer();
		}
		startAudioThread();

		mp.setOnPreparedListener(new OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer arg0) {

				mp.start();
				StrartbarUpdate();
				isPrepered = true;
			}

		});

		mp.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer arg0) {
				// TODO Auto-generated method stub

				closeAudio();
				isPrepered = false;
				Message msg = new Message();
				msg.what = STOP_PLAY;
				parentHandler.sendMessage(msg);
			}
		});

		mp.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub

				closeAudio();
				isPrepered = false;
				Message msg = new Message();
				msg.what = STOP_PLAY;
				parentHandler.sendMessage(msg);

				return false;
			}
		});
	}

	public void closeAudio() {

		if (mp == null)
			return;

		isPrepered = false;
		isPlaying = false;
		setPlayBtnResource(true);

		if (audioHandler != null)
			audioHandler.removeCallbacks(r);

		if (voiceThread != null) {
			voiceThread.interrupt();
			voiceThread = null;
		}

		// Thread thread = new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		//
		// if (mp != null) {
		// if (mp.isPlaying()) {
		mp.stop();
		mp.reset();
		// }
		mp.release();
		mp = null;
		// }
		// }
		// });
		//
		// thread.start();
	}

	public void reStartPlayAudio() {

		if (mp == null)
			return;

		isPlaying = true;
		isPauseing = false;
		setPlayBtnResource(false);
		StrartbarUpdate();
		mp.start();
	}

	public void pauseAudio() {

		if (mp == null)
			return;

		isPlaying = false;
		isPauseing = true;
		setPlayBtnResource(true);

		mp.pause();
	}

	public void startAudioThread() {
		voiceThread = new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					mp.setDataSource(audioObj.audioUrl);
					mp.prepare();

				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					Message msg = new Message();
					msg.what = 1;
					errorHandler.sendMessage(msg);

					e.printStackTrace();
				} catch (NullPointerException e) {
					Message msg = new Message();
					msg.what = 1;
					errorHandler.sendMessage(msg);

					e.printStackTrace();
				}
			}
		});

		voiceThread.start();
	}

	public Handler errorHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			if (msg.what == 1) {
				Toast.makeText(context,
						getResources().getString(R.string.audio_play_error),
						Toast.LENGTH_SHORT).show();

				setPlayBtnResource(true);

				Message msgAudio = new Message();
				msgAudio.what = STOP_PLAY;
				parentHandler.sendMessage(msgAudio);
			}
		};
	};

	Handler audioHandler = new Handler();

	public void StrartbarUpdate() {
		audioHandler.post(r);
	}

	Runnable r = new Runnable() {

		@Override
		public void run() {
			if (isPlaying) {
				int curTime = mp.getCurrentPosition();
				int maxTime = mp.getDuration();
				audioHandler.postDelayed(r, 10);

				int restTime = maxTime - curTime;
				String timeString = String.format("%02d:%02d",
						restTime / 1000 / 60, (restTime / 1000) % 60);

				Message msg = new Message();
				msg.what = UPDATE_TIME;
				msg.obj = timeString + "," + audioObj.name;
				parentHandler.sendMessage(msg);
			}
		}
	};

}
